package com.qire.manhua.model.viewModel.impl;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.view.View;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.SmartRefreshViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.BookshelfHistoryController;
import com.qire.manhua.dal.service.HomeBookshelfHistoryService;
import com.qire.manhua.databinding.LayoutHomeBookshelfHistoryItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

public class BookshelfHistoryViewModel extends SmartRefreshViewModel {

    private HomeBookshelfHistoryService historyService = new HomeBookshelfHistoryService(this);

    private final ArrayList<HistoryItemViewModel> historyList = new ArrayList();

    private final SummerRecyclerBindAdapter<HistoryItemViewModel> historyAdapter = new SummerRecyclerBindAdapter(historyList);

    private final ArrayList<String> batchDeleteList = new ArrayList<>();

    /** 编辑状态 */
    private boolean isEditing = false;

    /** 数据异常状态 */
    private boolean isException = false;

    private BookshelfViewModel bookshelfViewModel;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(BookshelfHistoryController controller) {
        historyAdapter.setEventProcess(controller);
        refreshUI();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        historyAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region    #业务数据处理 begin

    public void loadHistoryList() {
        historyService.loadBookshelfHistory();
    }

    public void clearHistoryList() {
        historyAdapter.notifyItemRangeRemoved(0, historyList.size());
        historyList.clear();
        // 防止状态不同步，由于页面切换回收等情况会导致项目列表重新生成并刷新状态。
        // 如果删除选项没有清楚会导致UI于删除内容不同步的问题。如果复杂情况下应该使用实时计算来获取选中的删除项个数。
        batchDeleteList.clear();
    }

    public void addHistoryItem(ComicBookEntity comicBookEntity, String lastReadRecord, long lastUpdateTime, String updateChapterInfo) {
        historyList.add(new HistoryItemViewModel(comicBookEntity, lastReadRecord, lastUpdateTime, updateChapterInfo));
    }

    public void refreshHistoryAdapter() {
        historyAdapter.notifyItemChanged(0, "full");
    }

    public void submitDelHistory() {
        historyService.batchRemoveBookshelfHistory(batchDeleteList);
        // 删除操作后列表列表没有可选数据时退出编辑状态
        if(ObjectUtil.nonNull(bookshelfViewModel) && batchDeleteList.size() >= historyList.size()) {
            bookshelfViewModel.closeEditMode();
        }
    }

    public void clearBatchDeleteList() {
        batchDeleteList.clear();
        refreshDeletePlateUI();
    }

    public boolean isEditing() {
        return isEditing;
    }

    public boolean isException() {
        return isException;
    }

    /**
     * 根据当前编辑状态判断下一步切换编辑状态的条件，如果没有可操作选项，则不允许进入编辑页。
     * @return true 为可进入编辑，false 不可进入编辑，只有当编辑状态位 false 且 收藏有内容时才可以编辑。
     */
    public boolean isAllowEdit() {
        return !isEditing && ListUtil.notEmpty(historyList);
    }

    public int batchDeleteCount() {
        return batchDeleteList.size();
    }

    //endregion #业务数据处理 end

    //region    #UI操作 begin

    /**
     * 切换编辑状态
     * @param isEditing true 进入编辑状态  false 退出编辑状态
     */
    public void toggleEditing(boolean isEditing) {
        this.isEditing = isEditing;
        refreshUI();
        historyAdapter.notifyItemRangeChanged(0, historyAdapter.getItemCount());
        if(!isEditing) {
            // 如果是退出编辑，则清空所有选中状态
            for(HistoryItemViewModel itemViewModel : historyList) {
                if(itemViewModel.isChecked()) {
                    itemViewModel.toggle();
                }
            }
        }
    }

    /**
     * 切换所有历史记录项选择状态
     */
    public void toggleCheckAll() {
        boolean isCheck = batchDeleteCount() == historyList.size();
        for(HistoryItemViewModel itemViewModel : historyList) {
            if(isCheck == itemViewModel.isChecked()) {
                itemViewModel.toggle();
            }
        }
    }

    public void refreshUI() {
        refreshEmptyDataUI(false);
        refreshDeletePlateUI();
    }

    public void refreshEmptyDataUI(boolean isException) {
        this.isException = isException;

        boolean isHistoryEmpty = ListUtil.isEmpty(historyList);

        set("dataContentPageNo", isHistoryEmpty ? 1 : 0);

        // 以下状态之需要考虑非正常数据的情况，因为之上已经做了页面切换，如果数据正常，则不会展示下面的内容。

        if(UserEntity.self.isLogin()) {
            set("emptyPanelIcon", isException ? R.drawable.app_common_pic_no_network : R.drawable.app_common_pic_no_history);
            set("emptyPanelBtnText", isException ? "点击重试" : "去书城看看");
        } else {
            set("emptyPanelIcon", R.drawable.app_common_pic_not_login);
            set("emptyPanelBtnText", "立即登录");
        }

    }

    public void refreshDeletePlateUI() {
        set("deletePlateVisible", isEditing ? View.VISIBLE : View.GONE);

        boolean isActive = ListUtil.notEmpty(batchDeleteList);

        set("deleteButtonIconColor", isActive ? ColorStateList.valueOf(Color.rgb(0xff, 0x90, 0x24)) : ColorStateList.valueOf(Color.rgb(0x5c,0x5c,0x5c)));
        set("deleteButtonText", "删除选中(" + batchDeleteCount() +")");
        set("deleteButtonTextColor", isActive ? "#ff9024" : "#5c5c5c");

        // 刷新父框架面板
        if(ObjectUtil.nonNull(bookshelfViewModel)) {
            bookshelfViewModel.toggleAllCheckUI(batchDeleteCount() >= historyList.size());
        }
    }

    public void setBookshelfViewModel(BookshelfViewModel bookshelfViewModel) {
        this.bookshelfViewModel = bookshelfViewModel;
        if(ObjectUtil.nonNull(bookshelfViewModel)) {
            bookshelfViewModel.toggleAllCheckUI(batchDeleteCount() >= historyList.size());
        }
    }
    //endregion #UI操作 end

    //region    #UI绑定 begin

    public MutableLiveData<Integer> getDeletePlateVisible() {
        return get("deletePlateVisible");
    }

    public MutableLiveData<ColorStateList> getDeleteButtonIconColor() {
        return get("deleteButtonIconColor");
    }

    public MutableLiveData<CharSequence> getDeleteButtonText() {
        return get("deleteButtonText");
    }

    public MutableLiveData<String> getDeleteButtonTextColor() {
        return get("deleteButtonTextColor");
    }

    public MutableLiveData<Integer> getDataContentPageNo(){
        return get("dataContentPageNo");
    }

    public MutableLiveData<Integer> getEmptyPanelIcon(){
        return get("emptyPanelIcon");
    }

    public MutableLiveData<String> getEmptyPanelBtnText() {
        return get("emptyPanelBtnText");
    }

    public Adapter getHistoryAdapter() {
        return historyAdapter;
    }

    public LayoutManager getHistoryLayoutManager() {
        return new LinearLayoutManager(null);
    }

    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_home_bookshelf_history_item)
    public class HistoryItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeBookshelfHistoryItemBinding> {

        public final ComicBookEntity comicBookEntity;

        private final String lastReadRecord;
        private final long   lastUpdateTime;
        private final String updateChapterInfo;

        private boolean isChecked = false;

        public HistoryItemViewModel(ComicBookEntity comicBookEntity, String lastReadRecord, long lastUpdateTime, String updateChapterInfo) {
            this.comicBookEntity    = comicBookEntity;
            this.lastReadRecord     = lastReadRecord;
            this.lastUpdateTime     = lastUpdateTime;
            this.updateChapterInfo  = updateChapterInfo;
        }

        public void toggle() {
            this.isChecked = !this.isChecked;
            if(isChecked) {
                batchDeleteList.add(String.valueOf(comicBookEntity.id));
            } else {
                batchDeleteList.remove(String.valueOf(comicBookEntity.id));
            }
            notifyPropertyChanged(BR.checkMarkIcon);
            refreshDeletePlateUI();
        }

        private boolean isChecked(){
            return isChecked;
        }

        @Override
        public void bindVariable(LayoutHomeBookshelfHistoryItemBinding viewBind) {
            viewBind.setHistoryItemViewModel(this);
        }

        @Bindable
        public int getEditCheckVisible() {
            return isEditing ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public int getCheckMarkIcon(){
            return isChecked() ? R.drawable.app_home_bookshelf_select_b : R.drawable.app_home_bookshelf_select_a;
        }

        @Bindable
        public String getBookCover() {
            return comicBookEntity.getCoverPlotVertical();
        }

        @Bindable
        public String getTitle(){
            return comicBookEntity.bookName;
        }

        @Bindable
        public CharSequence getLastReadRecord() {
            return "上次看到：" + lastReadRecord;
        }

        @Bindable
        public CharSequence getLastUpdateTime() {
            return StringUtil.friendlyDay(lastUpdateTime);
        }

        @Bindable
        public CharSequence getUpdateChapterInfo() {
            return "更新至" + updateChapterInfo;
        }

    }

}
